package
{
	import flash.display.MovieClip;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	/**
	 * ...
	 * @author ...
	 */
	public class Level1 extends Level_Base
	{
		const CAIR:Boolean=true;
		const SUBIR:Boolean=false;
		var porrete:MovieClip;
		var acaoporrete:Boolean;
		var limiteporreteY:int;
		var velocidadeY:Number;
		const GRAVIDADE:Number=6;
		const POS_INICIAL_PORRETE_X:int = 600;
		const POS_INICIAL_PORRETE_Y:int = 350;
		var esmagar:Boolean;
		
		var telaCanto:MovieClip;
		var paredeE:MovieClip;
		var paredeD:MovieClip;
		var chao:MovieClip;
		var cenario:MovieClip;
		var turret:Turret;
		var inimigo:Inimigo;
		var paredeManager:ParedeManager = new ParedeManager();
		var foods: Array = new Array();
		var foodState: Array = new Array();
		var qtdFood:int;
		const LIVRE:int = -2;
		const COM_PLAYER:int = -1;
			//player
		var player:MovieClip;
		const POS_INICIAL_PLAYER_X:Number=943;
		const POS_INICIAL_PLAYER_Y:Number=530;
		const VELOCIDADE_INICIAL_X:Number = -8;
		var velocidadeX:Number = VELOCIDADE_INICIAL_X;
		var vidasPlayer:int;
		
		//Jogo
		var qtdPraGanhar:int;
		var colisaoAtual:int;
		var qtdFrames:int;
		const INVISIVEL:int = -3;
		var comecou:Boolean = false;
		var terminou:Boolean = false;
		var food:MovieClip;
		var home:MovieClip;
		var fundoCavernaEnemies:MovieClip;
		var jaColidiu:Boolean;
		var enemyJaColidiu:Boolean;
		var posXPrimeira:int;
		var posYPrimeira:int;
		var criarVariosInimigos:Boolean=false;
		const GANHOU:Boolean = true;
		
		var enemyState: Array = new Array();
		var enemies: Array = new Array();
		var enemiesVelocidade: Array = new Array();
		const VELOCIDADE_ENEMIES:Number = -12;
		var qtdEnemies:int;
		const VIVO:int = -2;
		public function Level1()
		{
		
		}
		function acionarPorrete(keyboardEvent:KeyboardEvent):void
		{
			switch (keyboardEvent.keyCode)
			{
				case Keyboard.D :
					if (porrete.y <= POS_INICIAL_PORRETE_Y)
					{
						acaoporrete = CAIR;
						esmagar=true;
					}
					break;
			}
		}
		public override function start():void
		{
			desenharTela();
		}
		
		public function desenharTela():void
		{
			telaCanto = new TelaCanto();
			paredeE = new ParedeE();
			paredeD = new ParedeD();
			chao = new Chao();
			cenario = new Cenario();
			cenario.x = 514;
			cenario.y = 313;
			cenario.width=999;
			cenario.height=539;
			paredeD.x = 1006;
			paredeD.y = 296;
			paredeD.height += paredeD.height/3;
			paredeE.x = 22;
			paredeE.y = 314;
			paredeE.height += paredeE.height/4;
			chao.x = 514;
			chao.y = 556;
			chao.width += (4*chao.width/5)+16;
			telaCanto.x = paredeD.x - telaCanto.width/2;
			telaCanto.y = paredeD.y - (paredeD.height/2 - telaCanto.height/2);
			home = criarHome();
			criarFoods(20);
			food = foods[0];
			fundoCavernaEnemies = new FundoCavernaEnemies();
			fundoCavernaEnemies.x=856;
			fundoCavernaEnemies.y=510;
			fundoCavernaEnemies.visible=false;
			Main.instance.MC_tela.addChild(telaCanto);
			Main.instance.MC_tela.addChild(paredeE);
			Main.instance.MC_tela.addChild(paredeD);
			Main.instance.MC_tela.addChild(chao);
			Main.instance.MC_tela.addChild(cenario);
			Main.instance.MC_tela.addChild(fundoCavernaEnemies);
			
			
			Main.instance.stage.addEventListener(KeyboardEvent.KEY_DOWN,acionarPorrete);
			//Inicializa as variaveis da fase
			vidasPlayer=1;
			qtdEnemies=2;
			qtdFood=0;
			jaColidiu=false;
			enemyJaColidiu=false;
			qtdFrames=0;
			qtdPraGanhar=1;
			
			//Inicializa o player
			player=new Player();
			player.x = POS_INICIAL_PLAYER_X;
			player.y = POS_INICIAL_PLAYER_Y;
			//Inicializa o porrete
			porrete=new Porrete();
			porrete.x=POS_INICIAL_PORRETE_X;
			porrete.y=POS_INICIAL_PORRETE_Y;
			acaoporrete=SUBIR;
			limiteporreteY = 170;
			velocidadeY = 1;
			esmagar=true;
			//Adiciona os objetos na tela 
			Main.instance.MC_tela.addChild(player);
			Main.instance.MC_tela.addChild(porrete);
			//turret = new Turret();
			//turret.x = Main.instance.stage.stageWidth / 2;
			//turret.y = Main.instance.stage.stageHeight / 2;
			//Main.instance.MC_tela.addChild(turret);
			
			//Inimigo.criarInimigos(5);
		}
		
		public override function update():void
		{
				if((vidasPlayer <= 0 || verificarAcabouComida()) && qtdFood<qtdPraGanhar)
				{
					//perdeu
				}
				else if(qtdFood >= qtdPraGanhar)
				{
					//ganhou
				}
				else
				{
					telaCanto.vidasShow.text=vidasPlayer.toString();
					var qtdEnemyVivo:int=0;
					qtdFrames++;
					if(qtdFrames%48==0)
					{
						for(var j:int=0;j<enemies.length;j++){
							if(enemyState[j]==VIVO){
								qtdEnemyVivo++;
							}
						}
						if(qtdEnemyVivo<5)
						{
							criarEnemy();
						}
						qtdEnemyVivo=0;
					}
					for (var i:int=0; i<enemies.length; i++)
					{
						enemies[i].x +=  enemiesVelocidade[i];
					}
					//mostra o numero nas foods
					/*for(i=0;i<foods.length;i++){
						foods[i].foodNum.text=i.toString();
					}*/
					validarVelocidadeX();
					validarColisao();
					validarPorrete();
				}
			
			//turret.update(paredeManager);
			//Inimigo.updateinimigos(turret);
			//Collisions.verifyCollisions(turret);
		}
		
		function verificarAcabouComida():Boolean
		{
			for(var i:int=0;i<foodState.length;i++){
				if(foodState[i]!=INVISIVEL){
					return false;
				}
			}
			return true;
		}
		
		function validarPorrete():void
		{
			
			if (acaoporrete==CAIR)
			{
				validarVelocidadeporrete();
			}
			
			if (acaoporrete==SUBIR)
			{
				recolherporrete();
			}
		}
	
		function criarFoods(qtd:int):void
		{
			var posX:int;
			var posY:int;
			var food:MovieClip=new Food();
			for (var i:int=0; i<qtd; i++)
			{
				if (i==0)
				{
					posX=paredeE.x + ((paredeE.width/2) + (food.width/2))+ food.width;
					posY=chao.y - (chao.height/2) - (food.height/2);
					foods.push(criarSingleFood(posX,posY));

					foodState.push(LIVRE);
					posXPrimeira = posX;
					posYPrimeira = posY;
				}
				else if (i==1)
				{
					posX =paredeE.x + ((paredeE.width/2) + (food.width/2));
					posY=chao.y - (chao.height/2) - (foods[0].height/2);
					foods.push(criarSingleFood(posX,posY));
					foodState.push(LIVRE);
				}
				else
				{
					posX = foods[1].x;
					posY=chao.y - (chao.height/2) - (foods[1].height/2)-(foods[1].height*(i-1));
					foods.push(criarSingleFood(posX,posY));
					foodState.push(LIVRE);
				}
			}
		}
		function criarSingleFood(posX:int,posY:int):MovieClip
		{
			var food:MovieClip=new Food();
			food.x = posX;
			food.y = posY;
			//food.foodNum.text="a";
			Main.instance.MC_tela.addChild(food);
			return food;
		}
		
		function criarHome():MovieClip
		{
			var home:MovieClip=new Home();
			home.x= paredeD.x - (paredeD.width/2) ;
			home.y= chao.y - (chao.height/2) - (home.height/2);
			Main.instance.MC_tela.addChild(home);
			return home;
		}
		public override function terminate():void
		{
		}
		
		function validarColisao():void
		{

			if (player.hitTestObject(paredeE))
			{
				velocidadeX *= -1;
				player.x = paredeE.x + (paredeE.width/2) + (player.width/2);
				player.gotoAndStop(2);
			}
			if (player.hitTestObject(paredeD))
			{
				velocidadeX *= -1;
				player.x = paredeD.x - (paredeD.width/2) - (player.width/2);
				player.gotoAndStop(1);
			}
			if (player.hitTestObject(porrete)&&esmagar)
			{
				for(var n:int=0;n<foodState.length;n++)
				{
					if(foodState[n]==COM_PLAYER)
					{
						foods[n].x=paredeE.x + ((paredeE.width/2) + (food.width/2))+ food.width;
						foods[n].y=chao.y - (chao.height/2) - (foods[n].height/2);
						foodState[n]=LIVRE;
					}
				}
				velocidadeX = VELOCIDADE_INICIAL_X;
				player.x=POS_INICIAL_PLAYER_X;
				player.y=POS_INICIAL_PLAYER_Y;
				player.gotoAndStop(1);
				vidasPlayer--;
			}
			colisaoAtual=-1;
			for (var i:int=0; i<foods.length; i++)
			{
				
				//verifica se ja houve uma colisao do player com alguma food
				if (! jaColidiu)
				{
					if (player.hitTestObject(foods[i])&&foods[i].y!=(player.y-(player.width/2+foods[i].width/2))&&(foodState[i]==LIVRE || foodState[i]==COM_PLAYER)&&foodState[i]!=INVISIVEL)
					{
						velocidadeX *= -1;
						player.x = foods[i].x + (foods[i].width/2) + (player.width/2);
						player.gotoAndStop(2);
						foods[i].x = player.x;
						foods[i].y=player.y-(player.width/2+foods[i].width/2);
						jaColidiu = true;
						colisaoAtual = i;
						foodState[i] = COM_PLAYER;
						//trace("playerXbal="+i);
						//trace(foodState[i]);
					}
					else if (player.hitTestObject(foods[i])&&(foodState[i]==LIVRE || foodState[i]==COM_PLAYER)&&foodState[i]!=INVISIVEL)
					{
						foods[i].x = player.x;
						foods[i].y=player.y-(player.width/2+foods[i].width/2);
						jaColidiu = true;
						colisaoAtual = i;
						jaColidiu = true;
						foodState[i] = COM_PLAYER;
						//trace("playerXbal="+i);
						//trace(foodState[i]);
					}
				}
			}
			
			fazerRodizioFood();
			jaColidiu = false;
			//remove uma food caso ela chegue na casa do player e conta mais uma food no score
			for (i = 0; i<foods.length; i++)
			{
				if (foods[i].hitTestObject(home)&&foodState[i]!=INVISIVEL)
				{
					//trace("balXhome="+i);
					//MC_tela.removeChild(foods[i]);
					//foods.splice(i,1);
					foods[i].visible=false;
					//foodState.splice(i,1);
					foodState[i]=INVISIVEL;
					qtdFood++;
					telaCanto.qtdFoodShow.text = qtdFood.toString();

				}
			}

			colisaoAtual=-1;
			//valida colisoes dos inimigos
			for (i=0; i<enemies.length; i++)
			{
				//colisoes dos inimigos com a parede da esquerda
				if (enemies[i].hitTestObject(paredeE))
				{
					enemies[i].x = paredeE.x + (paredeE.width/2) + (enemies[i].width/2);
					enemiesVelocidade[i] *=  -1;
					enemies[i].gotoAndStop(2);
				}

				for (var j:int=0; j<foods.length; j++)
				{
					
					if (! enemyJaColidiu)
					{

						if (enemies[i].hitTestObject(foods[j])&&foods[j].y!=(enemies[i].y-(enemies[i].width/2+foods[j].width/2))&&(foodState[j]==LIVRE || foodState[j]==i)&&foodState[j]!=INVISIVEL  && enemyState[i]!=INVISIVEL )
						{
							
							enemiesVelocidade[i]*=-1;
							enemies[i].x = foods[j].x + (foods[j].width/2) + (enemies[i].width/2);
							enemies[i].gotoAndStop(2);
							foods[j].x = enemies[i].x;
							foods[j].y=enemies[i].y-(enemies[i].width/2+foods[j].width/2);
							enemyJaColidiu = true;
							jaColidiu=true;
							colisaoAtual = j;
							foodState[j] = i;
							//trace("enemy"+i+"Xbal="+j);
						}
						else if (enemies[i].hitTestObject(foods[j])&&(foodState[j]==LIVRE || foodState[j]==i)&&foodState[j]!=INVISIVEL  && enemyState[i]!=INVISIVEL )
						{
							foods[j].x = enemies[i].x;
							foods[j].y=enemies[i].y-(enemies[i].width/2+foods[j].width/2);
							jaColidiu = true;
							colisaoAtual = j;
							enemyJaColidiu = true;
							foodState[j] = i;
							//trace("enemy"+i+"Xbal="+j);
						}
					}
				}
				
				 enemyJaColidiu=false;
				//colisoes dos inimigos com o fundo de sua caverna
				if (enemies[i].hitTestObject(fundoCavernaEnemies)  && enemyState[i]!=INVISIVEL )
				{
					enemiesVelocidade[i] *=  -1;
					enemies[i].x = fundoCavernaEnemies.x - (fundoCavernaEnemies.width/2) - (enemies[i].width/2);
					enemies[i].gotoAndStop(1);
				}

				
			}
			//remove uma food caso ela chegue na casa do player e conta mais uma food no score
			for (i = 0; i<foods.length; i++)
			{
				if (foods[i].hitTestObject(cenario.entradaToca)&&foodState[i]!=COM_PLAYER && foodState[i]!=INVISIVEL)
				{
					//trace("balXhome="+i);
					//MC_tela.removeChild(foods[i]);
					//foods.splice(i,1);
					foods[i].visible=false;
					//foodState.splice(i,1);
					foodState[i]=INVISIVEL;
				}
			}
			
			fazerRodizioFood();
			jaColidiu=false;
			for(i=0;i<enemies.length;i++)
			{
				if((enemies[i].hitTestObject(porrete)&& esmagar) && enemyState[i]!=INVISIVEL)
				{
					for(var k:int=0;k<foodState.length;k++)
					{
						if(foodState[k]==i && foodState[k]!=INVISIVEL)
						{
							//MC_tela.removeChild(foods[k]);
							//foods.splice(k,1);
							//foods[k].visible=false;
							foods[k].x=paredeE.x + ((paredeE.width/2) + (food.width/2))+ food.width;
							foods[k].y=chao.y - (chao.height/2) - (foods[k].height/2);
							//foodState.splice(k,1);
							//foodState[k]=INVISIVEL;
							foodState[k]=LIVRE;
							//trace("removed food "+k);
						}
					}
					//MC_tela.removeChild(enemies[i]);
					//enemies.splice(i,1);
					matarEnemy(enemies[i]);
					enemyState[i]=INVISIVEL;
				}
				/*if(enemies[i].hitTestObject(porrete.porE)&& enemyState[i]!=INVISIVEL)
				{
					trace("E"+i+"XporE");
					enemiesVelocidade[i] *=  -1;
					enemies[i].x = porrete.x - (porrete.width/2) - (enemies[i].width/2);
					enemies[i].gotoAndStop(1);
					for(k=0;k<foodState.length;k++)
					{
						if(foodState[k]==i && foodState[k]!=INVISIVEL)
						{
							foods[k].x = enemies[i].x;
							foods[k].y=enemies[i].y-(enemies[i].width/2+foods[j].width/2);
						}
					}
					
				}*/
				if(enemies[i].hitTestObject(cenario.entradaToca)){
					if(enemiesVelocidade[i]<0){
						enemies[i].visible = true;
					}else{
						enemies[i].visible = false;
					}
					
					
				}

			}
			if (porrete.hitTestObject(chao))
			{
				porrete.y = chao.y - (chao.height/2) - (porrete.height/2);
				acaoporrete = SUBIR;
				esmagar=false;
			}
			
		}
		
		function criarEnemy():void
		{
			var posX:int;
			var posY:int;
			var enemy:MovieClip=new Enemy();
			posX = fundoCavernaEnemies.x + fundoCavernaEnemies.width / 2 + enemy.width / 2;
			posY=chao.y - (chao.height/2) - (enemy.height/2);
			enemy.x = posX;
			enemy.y = posY;
			enemy.visible=false;
			Main.instance.MC_tela.addChild(enemy);
			enemies.push(enemy);
			enemyState.push(VIVO);
			enemiesVelocidade.push(VELOCIDADE_ENEMIES);
		}

		function validarVelocidadeporrete():void
		{
			velocidadeY +=  GRAVIDADE;
			porrete.y +=  velocidadeY;
		}
		
		function recolherporrete():void
		{
			if (porrete.y > POS_INICIAL_PORRETE_Y)
			{
				porrete.y -= 4;
			}
		} 
		function validarVelocidadeX():void
		{
			player.x +=  velocidadeX;
		}
		function fazerRodizioFood()
		{
			//trace("fazer rodizio");
			if (jaColidiu && foods.length>1)
			{
				//trace("colisaoAtual="+colisaoAtual);
				for(var k:int=(foods.length-1);k>=0;k--)
				{
					if(foodState[k]==LIVRE)
					{
						foods[k].x = posXPrimeira;
						foods[k].y = posYPrimeira;
						//trace("k="+(k));
						return;
					}
				}
			}
		}
		function matarEnemy(enemy:MovieClip):void
		{
			enemy.x=0;
			enemy.y=0;
			enemy.visible=false;
		}
	}

}